/**
* COPYRIGHT. whx. ALL RIGHTS RESERVED.
* Project: just-core
* Author: whx <harrywu304@gmail.com>
* Create On: Apr 12, 2012 7:44:42 PM
*/

package org.justframework.core.mapper;

import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.JsonParser;
import org.codehaus.jackson.map.ObjectMapper;

/**
 * Textual json mapper
 */
public class JsonMapper implements Mapper {
	
	private static ObjectMapper mapper = null;
	
	static {
		JsonFactory jsonFactory = new JsonFactory();
		jsonFactory.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
		jsonFactory.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
		mapper = new ObjectMapper(jsonFactory);
	}

	/* (non-Javadoc)
	 * @see org.justframework.core.mapper.Mapper#toBean(byte[], java.lang.Class)
	 */
	@Override
	public <T> T toBean(String result, Class<T> clazz) {
		T rtv = null;
		try {
			rtv = mapper.readValue(result, clazz); 
		} catch (Exception ex) {  
			throw new IllegalArgumentException("map json to java bean fail", ex);
		}
		return rtv;	
	}

	/* (non-Javadoc)
	 * @see org.justframework.core.mapper.Mapper#toBytes(java.lang.Object)
	 */
	@Override
	public String toSerial(Object bean) {
		String rtv = null;
		try {
			rtv = mapper.writeValueAsString(bean);
		} catch (Exception ex) {  
			throw new IllegalArgumentException("map java bean to json fail", ex);
		}
		return rtv;	
	}

}
